<template>
  <div class="questions-container">
    <!-- 顶部导航和提问按钮 -->
    <div class="header">
      <h2>咨询问答系统</h2>
      <div class="actions">
        <el-button type="primary" @click="showQuestionDialog">
          <el-icon><Plus /></el-icon>
          我要提问
        </el-button>
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button value="card">
            <el-icon><Grid /></el-icon> 卡片视图
          </el-radio-button>
          <el-radio-button value="list">
            <el-icon><List /></el-icon> 列表视图
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 问题列表展示 -->
    <div v-if="loading" class="loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      加载中...
    </div>
    
    <div v-else-if="error" class="error">
      {{ error }}
    </div>
    
    <!-- 卡片视图 -->
    <div v-else-if="viewMode === 'card' && questions.length > 0" class="card-view">
      <el-row :gutter="20">
        <el-col v-for="q in questions" :key="q.id" :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="question-card" shadow="hover" @click="showQuestionDetail(q)">
            <div class="question-header">
              <h3>{{ q.content }}</h3>
              <div class="question-meta">
                <span class="meta-item">
                  <el-icon><User /></el-icon>
                  {{ q.studentId ? '学生提问' : '教师提问' }}
                </span>
                <span class="meta-item">
                  <el-icon><Clock /></el-icon>
                  {{ formatDate(q.create_time) }}
                </span>
              </div>
            </div>
            <div class="question-footer">
              <span>回答: {{ q.commentCount || 0 }}</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 列表视图 -->
    <div v-else-if="viewMode === 'list' && questions.length > 0" class="list-view">
      <el-table :data="questions" style="width: 100%">
        <el-table-column prop="content" label="问题内容" min-width="200">
          <template #default="{ row }">
            <div class="question-content" @click="showQuestionDetail(row)">{{ row.content }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="stu_id" label="提问者" width="120">
          <template #default="{ row }">
            {{ row.studentId ? '学生' : '教师' }}
          </template>
        </el-table-column>
        <el-table-column label="回答数" width="100">
          <template #default="{ row }">
            {{ row.commentCount || 0 }}
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <el-empty v-else description="暂无问题"></el-empty>

    <!-- 提问对话框 -->
    <el-dialog v-model="questionDialogVisible" title="提问" width="50%">
      <el-form :model="questionForm" label-width="80px">
        <el-form-item label="问题内容" required>
          <el-input v-model="questionForm.content" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="问题类型">
          <el-input v-model="questionForm.questionType"></el-input>
        </el-form-item>
        <el-form-item label="班级">
          <el-input v-model="questionForm.classId"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="questionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitQuestion">提交</el-button>
      </template>
    </el-dialog>

    <!-- 问题详情模态框 -->
    <el-dialog v-model="detailDialogVisible" :title="currentQuestion.content" width="70%" fullscreen>
      <div class="question-detail">
        <div class="question-content">
          <div class="question-meta">
            <span class="meta-item">
              <el-icon><User /></el-icon>
              {{ currentQuestion.studentId ? '学生提问' : '教师提问' }}
            </span>
            <span class="meta-item">
              <el-icon><Clock /></el-icon>
              {{ formatDate(currentQuestion.create_time) }}
            </span>
            <span class="meta-item">
              <el-icon><CollectionTag /></el-icon>
              {{ currentQuestion.question_type || '无分类' }}
            </span>
          </div>
        </div>

        <div class="answers-section">
          <h3>回答 ({{ totalComments || 0 }})</h3>
          
          <!-- 回答列表 -->
          <div v-if="pagedComments.length > 0" class="comment-list">
            <div v-for="comment in pagedComments" :key="comment.id" class="comment-item">
              <div class="comment-header">
                <span class="comment-author">{{ comment.studentId ? '学生' : '教师' }}</span>
                <span class="comment-time">{{ formatDate(comment.create_time) }}</span>
                <el-tag v-if="comment.has_adopt" type="success">已采纳</el-tag>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
              <div class="comment-actions">
                <el-button 
                  v-if="isQuestionOwner && !comment.has_adopt"
                  type="primary" 
                  size="small"
                  @click="adoptComment(comment.id)"
                >
                  <el-icon><CircleCheck /></el-icon>
                  采纳回答
                </el-button>
              </div>
            </div>
            
            <!-- 分页控件 -->
            <el-pagination
              v-if="totalComments > pageSize"
              small
              layout="prev, pager, next"
              :total="totalComments"
              :page-size="pageSize"
              v-model:current-page="currentPage"
              @current-change="handlePageChange"
            />
          </div>
          
          <el-empty v-else description="暂无回答"></el-empty>

          <!-- 回答表单 -->
          <div class="new-answer-section">
            <h3>提交回答</h3>
            <el-input
              v-model="newAnswer.content"
              type="textarea"
              :rows="5"
              placeholder="请输入您的回答..."
            ></el-input>
            <div class="submit-btn">
              <el-button type="primary" @click="submitAnswer">提交回答</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import {
  User, Clock, CollectionTag, Plus, 
  CircleCheck, Grid, List, Loading
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const questions = ref([])
const allComments = ref([]) // 存储所有评论
const loading = ref(true)
const error = ref(null)
const viewMode = ref('card') // 默认卡片视图

// 分页相关
const currentPage = ref(1)
const pageSize = 5
const totalComments = computed(() => allComments.value.length)

// 计算当前页的评论
const pagedComments = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return allComments.value.slice(start, end)
})

// 当前查看的问题详情
const currentQuestion = ref({
  id: null,
  content: '',
  create_time: '',
  stu_id: null,
  tea_id: null,
  question_type: ''
})

// 提问表单
const questionDialogVisible = ref(false)
const questionForm = ref({
  content: '',
  questionType: '',
  classId: ''
})

// 回答表单
const detailDialogVisible = ref(false)
const newAnswer = ref({
  content: '',
  questionId: null
})

const isQuestionOwner = ref(false)

// 加载所有问题
// 加载所有问题
const loadQuestions = async () => {
  try {
    loading.value = true
    error.value = null
    const response = await axios.get('/api/questions')
    
    // 获取每个问题的评论数量
    const questionsWithComments = await Promise.all(
      response.data.map(async question => {
        try {
          const commentsResponse = await axios.get(`/api/questions/${question.id}/comments`)
          return {
            ...question,
            commentCount: commentsResponse.data.length || 0
          }
        } catch (e) {
          console.error(`获取问题${question.id}的评论数失败:`, e)
          return {
            ...question,
            commentCount: 0
          }
        }
      })
    )
    
    questions.value = questionsWithComments
  } catch (err) {
    error.value = '加载问题列表失败: ' + err.message
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

// 获取问题详情和评论
// 获取问题详情和评论
const fetchQuestionDetail = async (questionId) => {
  try {
    // 获取问题详情
    const questionResponse = await axios.get(`/api/questions/${questionId}`)
    currentQuestion.value = questionResponse.data
    
    // 获取该问题的所有评论
    const commentsResponse = await axios.get(`/api/questions/${questionId}/comments`)
    allComments.value = commentsResponse.data
    currentPage.value = 1 // 重置到第一页
    
    newAnswer.value.questionId = questionId
    
    // 检查当前用户是否是问题所有者
    const userInfo = await fetchUserInfo()
    if (userInfo) {
      isQuestionOwner.value = (userInfo.isTeacher && currentQuestion.value.tea_id === userInfo.id) ||
                            (!userInfo.isTeacher && currentQuestion.value.stu_id === userInfo.id)
    }
    
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取问题详情失败: ' + error.message)
  }
}

// 分页变化处理
const handlePageChange = (newPage) => {
  currentPage.value = newPage
}

// 获取用户信息（教师或学生）
// 获取用户信息（教师或学生）
const fetchUserInfo = async () => {
  try {
    console.log('当前用户信息:', {
      userId: authStore.userId,
      userType: authStore.userType
    })
    
    // 确保authStore中有正确的用户类型
    if (!authStore.userType) {
      throw new Error('无法获取用户类型')
    }
    
    return {
      id: authStore.userId,
      isTeacher: authStore.userType === 'teacher' // 明确判断是否为教师
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

// 显示问题详情
const showQuestionDetail = (question) => {
  fetchQuestionDetail(question.id)
}

// 显示提问对话框
const showQuestionDialog = () => {
  questionForm.value = {
    content: '',
    questionType: '',
    classId: ''
  }
  questionDialogVisible.value = true
}

// 提交问题
const submitQuestion = async () => {
  try {
    const userInfo = await fetchUserInfo()
    if (!userInfo) {
      ElMessage.error('无法获取用户信息，请检查登录状态')
      return
    }
    
    const request = {
      content: questionForm.value.content,
      questionType: questionForm.value.questionType,
      classId: questionForm.value.classId
    }
    
    // 根据用户类型设置不同的字段
    if (userInfo.isTeacher) {
      request.teacherId = userInfo.id  // 教师提问
      request.studentId = null        // 明确设置为null
    } else {
      request.studentId = userInfo.id // 学生提问
      request.teacherId = null        // 明确设置为null
    }
    
    console.log('提交问题请求数据:', request) // 调试用
    
    const response = await axios.post('/api/questions', request)
    
    // 添加到问题列表前面
    questions.value.unshift({
      ...response.data,
      commentCount: 0,
      // 确保前端显示正确的提问者类型
      stu_id: userInfo.isTeacher ? null : userInfo.id,
      tea_id: userInfo.isTeacher ? userInfo.id : null
    })
    
    questionDialogVisible.value = false
    ElMessage.success('提问成功')
  } catch (error) {
    console.error('提问失败:', error)
    ElMessage.error('提问失败: ' + (error.response?.data?.message || error.message))
  }
}

// 采纳回答
const adoptComment = async (commentId) => {
  try {
    await axios.put(`/api/questions/comments/${commentId}/adopt`)
    // 重新加载评论列表以确保数据最新
    const commentsResponse = await axios.get(`/api/questions/${currentQuestion.value.id}/comments`)
    allComments.value = commentsResponse.data
    ElMessage.success('已采纳该回答')
  } catch (error) {
    ElMessage.error('采纳回答失败: ' + error.message)
  }
}

// 提交回答
// 提交回答
// 提交回答
const submitAnswer = async () => {
  if (!newAnswer.value.content.trim()) {
    ElMessage.warning('回答内容不能为空')
    return
  }

  try {
    const userInfo = await fetchUserInfo()
    if (!userInfo) {
      ElMessage.error('无法获取用户信息，请检查登录状态')
      return
    }
    
    if (!newAnswer.value.questionId) {
      ElMessage.error('无法确定要回答的问题')
      return
    }
    
    // 明确构建请求对象
    const request = {
      q_id: newAnswer.value.questionId,
      content: newAnswer.value.content
    }
    
    // 根据用户类型设置不同的ID字段
    if (userInfo.isTeacher) {
      request.tea_id = userInfo.id
    } else {
      request.stu_id = userInfo.id
    }
    
    console.log('提交评论请求数据:', request)
    
    await axios.post('/api/questions/comments', request)
    
    // 重新加载评论列表
    const commentsResponse = await axios.get(`/api/questions/${newAnswer.value.questionId}/comments`)
    allComments.value = commentsResponse.data
    currentPage.value = 1
    
    newAnswer.value.content = ''
    ElMessage.success('回答提交成功')
  } catch (error) {
    console.error('提交回答失败:', error)
    const errorMsg = error.response?.data?.message || 
                    error.response?.data?.error || 
                    error.message
    ElMessage.error(`提交回答失败: ${errorMsg}`)
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 初始化加载
onMounted(() => {
  loadQuestions()
})
</script>

<style scoped>
.questions-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.actions {
  display: flex;
  gap: 15px;
  align-items: center;
}

.loading, .error {
  text-align: center;
  padding: 50px 0;
  font-size: 16px;
}

.loading .el-icon {
  margin-right: 10px;
}

.card-view {
  margin-top: 20px;
}

.question-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  cursor: pointer;
}

.question-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.question-header {
  margin-bottom: 10px;
}

.question-header h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.question-meta {
  display: flex;
  gap: 15px;
  font-size: 14px;
  color: #666;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.question-footer {
  display: flex;
  justify-content: flex-end;
  font-size: 14px;
  color: #666;
}

.list-view {
  margin-top: 20px;
}

.question-content {
  cursor: pointer;
  line-height: 1.6;
}

/* 问题详情样式 */
.question-detail {
  padding: 20px;
}

.answers-section {
  margin-top: 30px;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  padding: 15px;
  margin-bottom: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.comment-author {
  font-weight: bold;
}

.comment-time {
  color: #999;
  font-size: 0.9em;
}

.comment-content {
  line-height: 1.6;
  margin-bottom: 10px;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
}

.new-answer-section {
  margin-top: 40px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.new-answer-section h3 {
  margin-bottom: 15px;
}

.submit-btn {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

/* 分页样式 */
.el-pagination {
  justify-content: center;
  margin-top: 20px;
}
</style>